<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="isHide ? 1 : 6" :xs="24" class="relative">
        <div class="app-container-tree-border">
          <project-tree-select-inner class="cd-mb8" :projectId="projectId" @changeProject="changeProject" />
          <el-tree :data="treeList" :props="defaultProps" ref="tree" node-key="id" highlight-current
            @node-click="handleNodeClick">
            <div slot-scope="{node, data}" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
          <div class="tree-hide-button iconfont" :class="isHide ? 'icon-xiangyou' : 'icon-xiangzuo'"
            @click="() => { isHide = !isHide }">
          </div>
        </div>
      </el-col>
      <el-col :span="isHide ? 23 : 18" :xs="24">
        <div class="app-container-table-border">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="期数" prop="settleIndex">
              <el-input v-model="queryParams.settleIndex" placeholder="请输入期数" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="期数名称" prop="settleName">
              <el-input v-model="queryParams.settleName" placeholder="请输入期数名称" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>


            <el-row :gutter="10" class="mb8 top-right-btn small-line-height">
              <el-col :span="1.5" v-show="queryParams.bdId">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                  v-hasPermi="['cm:bsQs:add']">新增</el-button>
              </el-col>
              <!-- <el-col :span="1.5" v-show="queryParams.bdId">
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                v-hasPermi="['cm:bsQs:export']">导出</el-button>
            </el-col> -->
            </el-row>
          </el-form>
          <el-table border stripe v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="期数" align="center" prop="settleName" min-width="180" />
            <!--          <el-table-column label="合同里程碑" align="center" prop="contractMilestoneName">-->
            <!--            <template slot-scope="scope">-->
            <!--              <span>{{ scope.row.contractMilestoneName ? scope.row.contractMilestoneName + "%" : "" }}</span>-->
            <!--            </template>-->
            <!--          </el-table-column>-->
            <el-table-column label="开始日期" align="center" prop="settleBeginDate" min-width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.settleBeginDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="结束日期" align="center" prop="settleEndDate" min-width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.settleEndDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否默认期数" align="center" prop="currentFlag" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.currentFlag == 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['cm:bsQs:edit']">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['cm:bsQs:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
      </el-col>
    </el-row>
    <!-- 添加或修改期数对话框 -->
    <jy-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="期数" prop="settleIndex">
          <el-input v-model="form.settleIndex" placeholder="请输入期数" disabled />
        </el-form-item>
        <el-form-item label="期数名称" prop="settleName">
          <el-input v-model="form.settleName" placeholder="请输入期数名称" disabled />
        </el-form-item>
        <el-form-item label="开始日期" prop="settleBeginDate">
          <el-date-picker clearable :disabled="haspermision" v-model="form.settleBeginDate" type="date"
            value-format="yyyy-MM-dd" placeholder="请选择开始日期" style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="settleEndDate">
          <el-date-picker clearable :disabled="haspermision" v-model="form.settleEndDate" type="date"
            value-format="yyyy-MM-dd" placeholder="请选择结束日期" style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <!--        <el-form-item label="合同里程碑" prop="contractMilestone">-->
        <!--          <el-select v-model="form.contractMilestone" placeholder="请选择合同里程碑" style="width: 100%;">-->
        <!--            <el-option v-for="item in milestoneOptions" :key="item.id" :label="item.kgyfkbl + '%'"-->
        <!--              :value="item.id"></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="是否默认期数" prop="currentFlag">
          <el-radio-group v-model="form.currentFlag">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </jy-dialog>
  </div>
</template>

<script>
import { queryBdSelect } from "@/api/base/bsBd";
import { listBsQs, getBsQs, delBsQs, addBsQs, updateBsQs, queryNewQs } from "@/api/cm/bsQs";
import { getMilestoneList } from "@/api/cm/bsContractInfoMilestone";

import { mapGetters } from "vuex";

export default {
  name: "BsQs",
  dicts: ['approval_status'],
  data () {
    return {
      isHide: false,
      haspermision: true,
      treeList: [],
      treeInfo: {},
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 期数表格数据
      dataList: [],
      milestoneOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bdId: undefined,
        settleIndex: undefined,
        settleName: undefined,
      },
      projectId: undefined,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        qsId: [
          { required: true, message: "期数id不能为空", trigger: "blur" }
        ],
        settleIndex: [
          { required: true, message: "期数不能为空", trigger: "blur" }
        ],
        settleName: [
          { required: true, message: "期数名称不能为空", trigger: "blur" }
        ],
        contractMilestone: [
          { required: true, message: "合同里程碑不能为空", trigger: "change" }
        ],
      }
    };
  },
  // 监听顶部全局下拉
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    sysProjectId (newVal, oldVal) {
      this.changeProject(newVal);
    }
  },
  created () {
    this.changeProject();
  },
  methods: {
    changeProject (projectId = this.sysProjectId) {
      this.projectId = projectId;
      this.projectChangeResetQuery();
      this.getBdList();
    },
    getBdList () {
      queryBdSelect({ projectId: this.projectId }).then(response => {
        this.treeList = response.data;
        // 选中左侧树
        this.$nextTick(() => {
          if (this.treeList.length > 0) {
            this.$refs.tree.setCurrentKey(this.treeList[0].id);
            this.handleNodeClick(this.treeList[0]);
          }
        });
      });
    },
    handleNodeClick (data) {
      this.queryParams.bdId = data.id;
      this.treeInfo = data;
      this.handleQuery();
      // this.getMilestoneOptions();
    },
    projectChangeResetQuery () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        bdId: undefined,
      };
      this.total = 0;
      this.dataList = [];
    },
    /** 查询期数列表 */
    getList () {
      this.loading = true;
      listBsQs(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
        //设置当前用户部门类别；
        if (this.dataList && this.dataList.length > 0) {
          this.haspermision = this.dataList[0].deptType == 2 ? true : false;
        }
      });
    },
    // 获取里程碑列表
    // getMilestoneOptions () {
    //   const param = {
    //     bdId: this.queryParams.bdId
    //   };
    //   getMilestoneList(param).then(response => {
    //     this.milestoneOptions = response.data;
    //   });
    // },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        qsId: undefined,
        settleIndex: undefined,
        settleName: undefined,
        settleBeginDate: undefined,
        settleEndDate: undefined,
        contractMilestone: undefined,
        remark: undefined,
        bdId: this.treeInfo.id,
        currentFlag: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.qsId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      queryNewQs(this.form.bdId).then(response => {
        const info = response.data;
        this.form.settleIndex = info.settleIndex;
        this.form.settleName = `第${info.settleIndex}期`;
        this.open = true;
        this.title = "添加期数";
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.loading = true;
      this.reset();
      const qsId = row.qsId || this.ids;
      getBsQs(qsId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改期数";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.qsId != null) {
            updateBsQs(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addBsQs(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const qsIds = row.qsId || this.ids;
      this.$modal.confirm('删除期数可能将关联的计量数据一并删除，确定要删除吗？').then(() => {
        this.loading = true;
        return delBsQs(qsIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('cm/bsQs/export', {
        ...this.queryParams
      }, `bsQs_${new Date().getTime()}.xlsx`);
    }
  }
};
</script>
